﻿
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;
using System;

namespace NWMES.HttpClientUtil
{
    public class SoapRequestHelper
    {

        public void startTest()
        {
            // --------------------------
            // 示例1：调用“获取用户信息”接口
            // --------------------------
            var getUserParams = new Dictionary<string, string>
        {
            { "UserId", "123" },    // WSDL 中定义的参数1
            { "UserName", "张三" }  // WSDL 中定义的参数2
        };
            string getUserResponse = SoapRequestHelper.CallSoapService(
                soapUrl: "http://127.0.0.1:8080/UserService.asmx",  // WSDL 中的接口地址
                soapAction: "http://127.0.0.1/UserService/GetUser",  // WSDL 中的 SOAPAction
                targetNamespace: "http://127.0.0.1/UserService",     // WSDL 中的命名空间
                methodName: "GetUser",                               // WSDL 中的方法名
                parameters: getUserParams
            );
            Console.WriteLine("获取用户响应：" + getUserResponse);

            // --------------------------
            // 示例2：调用“提交订单”接口（另一个接口，复用同一方法）
            // --------------------------
            var submitOrderParams = new Dictionary<string, string>
        {
            { "OrderId", "OD20240501" },
            { "Amount", "99.9" },
            { "Status", "1" }
        };
            string submitOrderResponse = SoapRequestHelper.CallSoapService(
                soapUrl: "http://127.0.0.1:8080/OrderService.asmx",
                soapAction: "http://127.0.0.1/OrderService/SubmitOrder",
                targetNamespace: "http://127.0.0.1/OrderService",
                methodName: "SubmitOrder",
                parameters: submitOrderParams
            );
            Console.WriteLine("提交订单响应：" + submitOrderResponse);
        }
        /// <summary>
        /// 通用 SOAP 接口调用（支持任意基于 WSDL 的 SOAP 1.1 接口）
        /// </summary>
        /// <param name="soapUrl">WSDL 中定义的接口地址（如 http://xxx/Service.asmx）</param>
        /// <param name="soapAction">WSDL 中定义的 SOAPAction（如 http://xxx/Service/GetUser）</param>
        /// <param name="targetNamespace">WSDL 中定义的目标命名空间（如 http://xxx/Service）</param>
        /// <param name="methodName">WSDL 中定义的接口方法名（如 GetUser）</param>
        /// <param name="parameters">接口参数（键=参数名，值=参数值）</param>
        /// <returns>SOAP 接口返回的原始 XML 响应</returns>
        public static string CallSoapService(string soapUrl, string soapAction,
                                            string targetNamespace, string methodName,
                                            Dictionary<string, string> parameters)
        {
            try
            {
                // 1. 构造 SOAP XML 报文（按 WSDL 定义的命名空间和方法名）
                XNamespace soapEnv = "http://schemas.xmlsoap.org/soap/envelope/";
                XNamespace ser = targetNamespace;

                // 构造 SOAP Body 中的方法节点和参数节点
                XElement methodNode = new XElement(ser + methodName);
                foreach (var param in parameters)
                {
                    // 按 WSDL 定义的参数名添加子节点
                    methodNode.Add(new XElement(ser + param.Key, param.Value));
                }

                // 构造完整 SOAP Envelope
                XDocument soapXml = new XDocument(
                    new XDeclaration("1.0", "utf-8", null),
                    new XElement(soapEnv + "Envelope",
                        new XAttribute(XNamespace.Xmlns + "soapenv", soapEnv.NamespaceName),
                        new XAttribute(XNamespace.Xmlns + "ser", ser.NamespaceName),
                        new XElement(soapEnv + "Header"),
                        new XElement(soapEnv + "Body", methodNode)
                    )
                );

                // 2. 转换 XML 为字符串
                string soapXmlStr;
                using (var sw = new StringWriter())
                {
                    soapXml.Save(sw);
                    soapXmlStr = sw.ToString();
                }

                // 3. 用 HttpWebRequest 发送 POST 请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(soapUrl);
                request.Method = "POST";
                request.ContentType = "text/xml; charset=utf-8";
                request.Headers.Add("SOAPAction", soapAction);
                request.Timeout = 30000;

                // 写入请求体
                byte[] requestBytes = Encoding.UTF8.GetBytes(soapXmlStr);
                request.ContentLength = requestBytes.Length;
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(requestBytes, 0, requestBytes.Length);
                }

                // 4. 接收响应
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"SOAP 接口调用失败：{ex.Message}", ex);
            }
        }


    }
}
